
////  LLPhotoBrowserCell.swift
////  WeiBoShiBing
////
////  Created by Bingo on 15/11/8.
////  Copyright © 2015年 Bingo. All rights reserved.
////
//
import UIKit

let CZPhotoBrowserCellMinimumZoomScale: CGFloat = 0.5

class LLPhotoBrowserCell: UICollectionViewCell {
    
    
    weak var cellDelegate:LLPhotoBrowserCellDelegate?
    
    var photoModel:LLPhotoBrowserModel?{
        didSet{
        
            guard let imageURL = photoModel?.url else{
                
                print("imageURL为空")
                return
            }
            
            //清空图片数据防止cell重用
            imageView.image = nil
            resetScrollView()
            indicator.startAnimating()
           self.imageView.sd_setImageWithURL(imageURL) { (image, error, _, _) -> Void in
                
                self.indicator.stopAnimating()
                if error != nil {
                    print("下载大图片出错:error: \(error), url:\(imageURL)")
                    return
                }
                print("下载成功")
//            let date = UIImagePNGRepresentation(image)
//            print("\(date)----------")
                self.layoutImageView(image)
            }
            
        }
    
    }
    
//        private func testAfter() {
//            // 模拟网络延时
//            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue()) { () -> Void in
//                // 使用sd去下载
//                self.imageView.sd_setImageWithURL(imageURL) { (image, error, _, _) -> Void in
//                    // 关闭指示器
//                    self.indicator.stopAnimating()
//                    if error != nil {
//                        print("下载大图片出错:error: \(error), url:\(imageURL)")
//                        return
//                    }
//    
//                    // 下载成功, 设置imageView的大小
//                    print("下载成功")
//                    self.layoutImageView(image)
//                }
//            }
//        }
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        perpareUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func layoutImageView(image:UIImage){
    
        let size = image.displaySize()
        
        if size.height < UIScreen.mainScreen().bounds.height{
        
            let offestY = (UIScreen.mainScreen().bounds.height - size.height) * 0.5
            
            imageView.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)
            scrollview.contentInset = UIEdgeInsets(top: offestY, left: 0, bottom: offestY, right: 0)
            
        }else{
        
        imageView.frame = CGRect(origin: CGPointZero, size: size)
    
        scrollview.contentSize = size
        }
    }
    
    private func displaySize(image:UIImage) ->CGSize{
    
        let newWidth = UIScreen.mainScreen().bounds.width
        
        let newHeight = newWidth * image.size.height / image.size.width
        
        let newSize = CGSize(width: newWidth, height: newHeight)
        
        return newSize
    }
    
    private func perpareUI(){
    
        contentView.addSubview(scrollview)
        scrollview.addSubview(imageView)
        contentView.addSubview(indicator)
        
        scrollview.maximumZoomScale = 2
        scrollview.minimumZoomScale = 0.5
        scrollview.delegate = self
        scrollview.bounces = false
        
        
        scrollview.translatesAutoresizingMaskIntoConstraints = false
        indicator.translatesAutoresizingMaskIntoConstraints = false
        
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[sv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics:nil , views: ["sv" : scrollview]))
        
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[sv]-0-|", options: NSLayoutFormatOptions(rawValue:0), metrics: nil, views: ["sv" : scrollview]))
        
        
        contentView.addConstraint(NSLayoutConstraint(item: indicator, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
        
        contentView.addConstraint(NSLayoutConstraint(item: indicator, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0))

        
    }
    
    private func resetScrollView(){
        
        scrollview.contentInset = UIEdgeInsetsZero
        scrollview.contentSize = CGSizeZero
        scrollview.contentOffset = CGPointZero
        imageView.transform = CGAffineTransformIdentity
        
    }
    
    private lazy var scrollview = UIScrollView()
    
    lazy var imageView:LLImageView = LLImageView()
    
    private lazy var indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
}

protocol LLPhotoBrowserCellDelegate: NSObjectProtocol{
    
    func viewForTransparent()->UIView
    
    func cellDismiss()

}

extension LLPhotoBrowserCell:UIScrollViewDelegate{
    
    func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
        return imageView
    }
    //scrollview缩放时调用
    func scrollViewDidZoom(scrollView: UIScrollView) {
    
            let view = cellDelegate?.viewForTransparent()
        
        if imageView.transform.a < 1{
        
            view?.alpha = imageView.transform.a * 0.7 - 0.2
        }else{
            
            view?.alpha = 1
        }
    }
    //scrollview结束时调用
    func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) {

        //注意bouns和frame的使用
//        print("imageView.frame:\(imageView.frame)")
//        print("imageView.bounds:\(imageView.bounds)")
//        缩放后frame会改变.bounds不会改变
        var offestY = (scrollView.bounds.height - imageView.frame.height) * 0.5
        var offestX = (scrollView.bounds.width - imageView.frame.width) * 0.5
        
        if offestY < 0 {
            offestY = 0
        }
        
        if offestX < 0 {
            offestX = 0
        }
        //        offestY = offestY < 0 ? 0:offestY
        //        offestX = offestX < 0 ? 0:offestX
        
        if imageView.transform.a < 0.7{
        
            let thumbImage = photoModel!.imageView!
            
            let rect = thumbImage.superview!.convertRect(thumbImage.frame, toCoordinateSpace: self)
            
            UIView.animateWithDuration(0.25, animations: { () -> Void in
                
                self.imageView.frame = CGRect(x: 0, y: 0, width: rect.width, height: rect.height)
                self.scrollview.contentOffset.x = -rect.origin.x
                self.scrollview.contentOffset.y = -rect.origin.y
                
                self.scrollview.contentInset = UIEdgeInsets(top: rect.origin.y, left: rect.origin.x, bottom: 0, right: 0)
                
                }, completion: { (_) -> Void in
                    
                    self.cellDelegate?.cellDismiss()
                    
            })
        }else{
        
        UIView.animateWithDuration(0.25) { () -> Void in
            
            scrollView.contentInset = UIEdgeInsets(top: offestY, left: offestX, bottom: offestY, right: offestX)
        }
    
      }
    }

}
